package com.haian.slidealbum.control;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.haian.slidealbum.R;
import com.haian.slidealbum.common.ConstCommon;
import com.haian.slidealbum.model.adapter.AdapterImageManage;
import com.haian.slidealbum.model.helper.DBHandler;
import com.haian.slidealbum.model.object.ObjectImage;

public class ImageManageActivity extends Activity implements OnClickListener {

	TextView txtItemSelected;
	ImageView btnAdd, btnEdit;
	GridView listImage;
	ArrayList<ObjectImage> arrayItem, listImageSelected;
	AdapterImageManage adapter;
	int idAlbum;
	Context mContext;
	Dialog dialog;
	int ADD_NEW_ITEM;
	String cbSelected_Selected;

	// _______________________ System Fuction ________________________________

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_image_manage);
		overridePendingTransition(R.drawable.activity_transaction_trans_left_in, R.drawable.activity_transaction_trans_left_out);
		initDB();
		initWidget();
	}

	@Override
	public void onBackPressed() {
	    super.onBackPressed();
	    overridePendingTransition(R.drawable.activity_transaction_trans_right_in, R.drawable.activity_transaction_trans_right_out);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnAdd:
			listImageSelected.clear();
			txtItemSelected.setVisibility(View.INVISIBLE);
			showDialogSelectAddressImport();
			break;
		case R.id.btnEdit:
			showScreenDelete();
			break;

		default:
			break;
		}

	}

	@Override
	protected void onResume() {
		try {
			if(FlickrAlbumUpdateActivity.KEY_FOR_RESUM_ALBUM)
			{
				FlickrAlbumUpdateActivity.KEY_FOR_RESUM_ALBUM = false;
				if(FlickrAlbumUpdateActivity.KEY_ID_RESUM_ALBUM > 0)
				{
					FlickrAlbumUpdateActivity.KEY_ID_RESUM_ALBUM = 0;
					arrayItem.clear();
					arrayItem.addAll(getDBItem(idAlbum));
					adapter.notifyDataSetChanged();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onResume();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ADD_NEW_ITEM) {
			if (resultCode == RESULT_OK) {
				try {
					int idAlbum = data.getIntExtra(ConstCommon.KEY_RESULT_ID_ALBUM, -1);
					arrayItem.clear();
					arrayItem.addAll(getDBItem(idAlbum));
					adapter.notifyDataSetChanged();
					if (checkAlbumIsCurrentAlbum(idAlbum)) {
						WidgetUpdateService.statusCurrentAlbum = true;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}

	}

	// _______________________________- Custom Function ________________________

	private void initWidget() {
		txtItemSelected = (TextView)findViewById(R.id.txtItemSelected);
		txtItemSelected.setVisibility(View.INVISIBLE);
		btnAdd = (ImageView) findViewById(R.id.btnAdd);
		btnAdd.setOnClickListener(this);
		btnEdit = (ImageView) findViewById(R.id.btnEdit);
		btnEdit.setOnClickListener(this);
		listImage = (GridView) findViewById(R.id.listImage);
		adapter = new AdapterImageManage(ImageManageActivity.this, arrayItem);
		listImage.setAdapter(adapter);
		listImage.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				showDialogChangeCover(arrayItem.get(position).getIdImage(), String.valueOf(idAlbum));
				return false;
			}
		});
		listImage.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (dialog == null || dialog.isShowing() == false) {
					Intent intent = new Intent(mContext, ImageViewDetailActivity.class);
					intent.putExtra(ConstCommon.KEY_POSITION, position);
					intent.putParcelableArrayListExtra(ConstCommon.KEY_ARRAY_IMAGE, (ArrayList<? extends Parcelable>) arrayItem);
					mContext.startActivity(intent);
				}
			}
		});
	}

	private void initDB() {
		Intent intent = new Intent();
		intent = getIntent();
		idAlbum = intent.getExtras().getInt(ConstCommon.KEY_RESULT_ID_ALBUM);
		mContext = this;
		arrayItem = new ArrayList<ObjectImage>();
		listImageSelected = new ArrayList<ObjectImage>();
		arrayItem = getDBItem(idAlbum);

	}

	private ArrayList<ObjectImage> getDBItem(int idAlbum) {
		ArrayList<ObjectImage> arrayItem = new ArrayList<ObjectImage>();
		try {
			Cursor mCursorItem = DBHandler.getItemByAlbumId(mContext, String.valueOf(idAlbum));
			if (mCursorItem.moveToFirst()) {
				do {
					ObjectImage mObjectItem = new ObjectImage();
					mObjectItem.setIdImage(mCursorItem.getInt(0));
					mObjectItem.setUrlImage(mCursorItem.getString(1));
					
					mObjectItem.setCheckDelete(false);
					mObjectItem.setIsSelected(false);
					
					arrayItem.add(mObjectItem);
				} while (mCursorItem.moveToNext());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return arrayItem;
	}

	void showScreenDelete()
	{
		try {
			if(listImageSelected.size() > 0)
			{
				showDialogDeleteAlbum();
			}else if(arrayItem.size() > 0)
			{
				ArrayList<ObjectImage> arrayItemTemp = new ArrayList<ObjectImage>();
				for(int i=0; i< arrayItem.size(); i++)
				{
					ObjectImage mObjectImage = new ObjectImage();
					mObjectImage = arrayItem.get(i);
					mObjectImage.setCheckDelete(true);
					mObjectImage.setIsSelected(false);
					arrayItemTemp.add(mObjectImage);
				}
				arrayItem.clear();
				arrayItem.addAll(arrayItemTemp);
				adapter.notifyDataSetChanged();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	public ArrayList<ObjectImage> getListImageSelected() {
		listImageSelected = new ArrayList<ObjectImage>();
		try {
			if (arrayItem.size() > 0) {
				for (int i = 0; i < arrayItem.size(); i++) {
					if (arrayItem.get(i).getIsSelected()) {
						listImageSelected.add(arrayItem.get(i));
					}
				}
			}
			txtItemSelected.setVisibility(View.VISIBLE);
			txtItemSelected.setText(listImageSelected.size() + " " + getResources().getString(R.string.selected));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listImageSelected;
	}
	
	void showDialogDeleteAlbum() {
		try {
			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.delete_image));
			dialog.setContentView(R.layout.dialog_delete);
			Button dialog_BtnYes = (Button) dialog.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog.findViewById(R.id.dialog_BtnNo);
			dialog_BtnYes.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					if(listImageSelected.size() > 0)
					{
						for(int i=0; i< listImageSelected.size(); i++)
						{
							ObjectImage mObjectImage = listImageSelected.get(i);
							DBHandler.deleteItemById(mContext, mObjectImage.getIdImage());
							arrayItem.remove(mObjectImage);
						}
						ArrayList<ObjectImage> arrayItemTemp = new ArrayList<ObjectImage>();
						for(int i=0; i< arrayItem.size(); i++)
						{
							ObjectImage mObjectImage = new ObjectImage();
							mObjectImage = arrayItem.get(i);
							mObjectImage.setCheckDelete(false);
							mObjectImage.setIsSelected(false);
							arrayItemTemp.add(mObjectImage);
						}
						arrayItem.clear();
						arrayItem.addAll(arrayItemTemp);
						adapter.notifyDataSetChanged();
						listImageSelected.clear();
						txtItemSelected.setVisibility(View.INVISIBLE);
					}
					dialog.dismiss();
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	boolean checkAlbumIsCurrentAlbum(int idAlbum) {
		try {
			Cursor mCursorAlbum = DBHandler.getAlbumById(mContext, idAlbum);
			if (mCursorAlbum.moveToFirst()) {
				if (mCursorAlbum.getString(2).equals("1")) {
					return true;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}
	void showDialogChangeCover(final int idItem, final String idAlbum)
	{
		try {
			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.change_album));
			dialog.setContentView(R.layout.dialog_item_cover);
			final CheckBox cbItemCover = (CheckBox) dialog
					.findViewById(R.id.cbItemCover);
			Button dialog_BtnYes = (Button) dialog.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog.findViewById(R.id.dialog_BtnNo);
			
			Cursor mCursorItem = DBHandler.getItemById(mContext, idItem);
			if (mCursorItem.moveToFirst()) {
				cbItemCover.setChecked(false);
				if (mCursorItem.getString(3).equals("1")) {
					cbItemCover.setChecked(true);
					cbItemCover.setEnabled(false);
				}
			}
			dialog_BtnYes.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String currentItem = "1";
					if(cbItemCover.isChecked())
					{
						currentItem = "1";
						DBHandler.disableCurrentAlbum(mContext);
					}else{
						currentItem = "0";
					}
					
					DBHandler.updateItemCover(mContext, idItem, idAlbum, currentItem);
//					
//					WallpaperManager mWallpaperManager = WallpaperManager.getInstance(mContext);
//
//					try {
//					    mWallpaperManager.setBitmap(bmap);
//					} catch (IOException e) {
//					    e.printStackTrace();
//					}
					
					dialog.dismiss();
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});

			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	void showDialogSelectAddressImport()
	{
		try {
			final String cbGallery_Selected = mContext.getResources().getString(R.string.gallery);
			final String cbFacebook_Selected = mContext.getResources().getString(R.string.facebook);
			final String cbFlick_Selected = mContext.getResources().getString(R.string.flick);
			final String cbInstagram_Selected = mContext.getResources().getString(R.string.instagram);
			cbSelected_Selected = cbGallery_Selected;
			
			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.app_name));
			dialog.setContentView(R.layout.dialog_select_import);
			Button dialog_BtnYes = (Button) dialog.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog.findViewById(R.id.dialog_BtnNo);
			RadioGroup cbGroup = (RadioGroup)dialog.findViewById(R.id.cbGroup);
			cbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
			{
			    public void onCheckedChanged(RadioGroup cbGroup, int checkedId)
			    {
			        RadioButton cbSelected = (RadioButton)cbGroup.findViewById(checkedId);
			        if(cbSelected.isChecked())
			        {
			        	cbSelected_Selected = cbSelected.getText().toString();
			        }
			    }
			});
			
			dialog_BtnYes.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(cbSelected_Selected.equals(cbGallery_Selected))
					{
						showImageGallery();
					}else if(cbSelected_Selected.equals(cbFacebook_Selected))
					{
						showImageFacebook();
					}else if(cbSelected_Selected.equals(cbFlick_Selected))
					{
						showImageFlickr();
					}else if(cbSelected_Selected.equals(cbInstagram_Selected))
					{
						showImageInstagram();
					}
					dialog.dismiss();
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void showImageGallery() {
		Intent intent = new Intent(this, FolderImageActivity.class);
		intent.putExtra(ConstCommon.KEY_FROM_WHERE_ITEM_ID_ALBUM, idAlbum);
		intent.putExtra(ConstCommon.KEY_FROM_WHERE_ITEM, ConstCommon.KEY_FROM_WHERE_ITEM);
		startActivityForResult(intent, ADD_NEW_ITEM);
	}
	
	void showImageFacebook()
	{
		Intent intent = new Intent(this, FacebookAlbumUpdateActivity.class);
		intent.putExtra(ConstCommon.KEY_FROM_WHERE_ITEM_ID_ALBUM, idAlbum);
		startActivityForResult(intent, ADD_NEW_ITEM);
	}
	
	void showImageInstagram()
	{
		Intent intent = new Intent(this, InstagramUpdateActivity.class);
		intent.putExtra(ConstCommon.KEY_FROM_WHERE_ITEM_ID_ALBUM, idAlbum);
		startActivityForResult(intent, ADD_NEW_ITEM);
	}
	
	void showImageFlickr()
	{
		Intent intent = new Intent(this, FlickrAlbumUpdateActivity.class);
		intent.putExtra(ConstCommon.KEY_FROM_WHERE_ITEM_ID_ALBUM, idAlbum);
		startActivityForResult(intent, ADD_NEW_ITEM);
	}
}
